const { defineConfig } = require('@vue/cli-service')
const http = require('http')
const https = require('https')
const { URL } = require('url')
module.exports = defineConfig({
  transpileDependencies: true,
  configureWebpack: {
    plugins: [
      new (require('webpack')).DefinePlugin({
        'process.env.VUE_APP_USE_MOCK': JSON.stringify('false'),
        'process.env.VUE_APP_API_BASE_URL': JSON.stringify('http://localhost:8080')
      })
    ]
  },
  devServer: {
    port: 8079,
    host: '0.0.0.0',
    proxy: {
      // API代理配置
      '/api': {
        target: 'http://localhost:8080',
        changeOrigin: true,
        pathRewrite: {
          '^/api': ''
        }
      },
      // 统一通过 /proxy 代理外部资源，解决CORS
      '/proxy': {
        target: 'http://localhost:8080', // 会被忽略，实际使用完整URL重写
        changeOrigin: true,
        pathRewrite: {
          '^/proxy': ''
        },
        router: (req) => {
          // 动态代理到真实外部域名：/proxy/https://host/path -> https://host/path
          const url = req.url.replace(/^\/proxy\//, '')
          try {
            const u = new URL(url)
            return `${u.protocol}//${u.host}`
          } catch (e) {
            return undefined
          }
        },
        onProxyReq(proxyReq, req) {
          // 将路径改写为真实路径
          const raw = req.url.replace(/^\/proxy\//, '')
          try {
            const u = new URL(raw)
            proxyReq.path = u.pathname + (u.search || '')
          } catch (e) {}
        }
      }
    },
    onBeforeSetupMiddleware(devServer) {
      const app = devServer.app
      // 开发期直连外部带签名URL的中转（不篡改查询串）
      app.get('/cos', (req, res) => {
        const raw = req.query && req.query.url
        if (!raw) {
          res.status(400).send('url required')
          return
        }
        let target
        try {
          target = new URL(raw)
        } catch (e) {
          res.status(400).send('invalid url')
          return
        }
        const lib = target.protocol === 'https:' ? https : http
        const proxyReq = lib.request(target, (proxyRes) => {
          res.status(proxyRes.statusCode || 200)
          const headersToCopy = [
            'content-type',
            'content-length',
            'accept-ranges',
            'content-range',
            'cache-control',
            'last-modified'
          ]
          headersToCopy.forEach((h) => {
            if (proxyRes.headers[h]) res.setHeader(h, proxyRes.headers[h])
          })
          // 允许前端读取
          res.setHeader('Access-Control-Allow-Origin', '*')
          proxyRes.pipe(res)
        })
        proxyReq.on('error', () => {
          res.status(502).send('proxy error')
        })
        proxyReq.end()
      })
    }
  }
})
